//package com.demo.demo;
//
///**
// * Copyright
// *
// * @Author WuHuang
// * @Date 2023/2/28
// */
//
//import cn.hutool.core.date.DateUtil;
//import com.alibaba.fastjson.JSONObject;
//import io.netty.util.internal.StringUtil;
//import lombok.extern.slf4j.Slf4j;
//import okhttp3.HttpUrl;
//import org.springframework.http.HttpEntity;
//import sun.net.www.http.HttpClient;
//
//import java.io.BufferedReader;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.IOException;
//import java.io.InputStreamReader;
//import java.io.UnsupportedEncodingException;
//import java.nio.file.Files;
//import java.nio.file.Paths;
//import java.security.KeyFactory;
//import java.security.NoSuchAlgorithmException;
//import java.security.PrivateKey;
//import java.security.PublicKey;
//import java.security.Signature;
//import java.security.cert.CertificateFactory;
//import java.security.cert.X509Certificate;
//import java.security.spec.InvalidKeySpecException;
//import java.security.spec.PKCS8EncodedKeySpec;
//import java.util.Base64;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * 微信验签工具类
// */
//@Slf4j
//public class CheckSignUtil {
//    private static String CHARSET_ENCODING = "UTF-8";
//    private static String ALGORITHM = "SHA256withRSA";
//
//    public static void main(String[] args) throws Exception {
//        getCheckSign("商户号", "https://api.mch.weixin.qq.com/v3/certificates", 2, null, "商户证书序列号", "D:\\wxpert\\apiclient_key.pem");
//    }
//
//    public static Boolean getCheckSign(String merchantId, String url, int timeout, String body, String certSerialNo, String keyPath) throws UnsupportedEncodingException, Exception {
//        String result = "";
//        boolean verify=false;
//        //创建http请求
//        HttpGet httpGet = new HttpGet(url);
//        httpGet.addHeader("Content-Type", "application/json");
//        httpGet.addHeader("Accept", "application/json");
//
//        //设置认证信息
//        httpGet.setHeader("Authorization", "WECHATPAY2-SHA256-RSA2048" + " " + getToken("GET", url, null, merchantId, certSerialNo, keyPath));
//
//        //设置请求器配置:如超时限制等
//        RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout * 1000).setConnectTimeout(timeout * 1000).build();
//        httpGet.setConfig(config);
//        try {
//            CloseableHttpClient httpClient = HttpClients.createDefault();
//            CloseableHttpResponse response = httpClient.execute(httpGet);
//            HttpEntity httpEntity = response.getEntity();
//            result = EntityUtils.toString(httpEntity, "UTF-8");
//            Header[] allHeaders = response.getAllHeaders();
//            Map<String, String> headers = new HashMap<String, String>();
//            for (int i = 0; i < allHeaders.length; i++) {
//                String key = allHeaders[i].getName();
//                String value = allHeaders[i].getValue();
//                headers.put(key, value);
//            }
//            String Nonce = headers.get("Wechatpay-Nonce");
//            String Signature = headers.get("Wechatpay-Signature");
//            String Timestamp = headers.get("Wechatpay-Timestamp");
//            String srcData = Timestamp + "\n"
//                    + Nonce + "\n"
//                    + result + "\n";
//            // publicKeyPath 为自己公钥保存的地址如：D:\key\publicKey.pem
//            String publicKeyPath = "D:\\key\\publicKey.pem";
//            verify = verify(srcData, Signature, publicKeyPath);
//            log.info("验签结果 = " + verify);
//        } catch (Exception e) {
//            log.error("======验签getCheckSign出现异常=======",e);
//        }
//        return verify;
//    }
//
//    /**
//     * 验签
//     *
//     * @param srcData
//     * @param signedData
//     * @param publicKeyPath
//     * @return
//     */
//    public static boolean verify(String srcData, String signedData, String publicKeyPath) {
//        if (srcData == null || signedData == null || publicKeyPath == null) {
//            return false;
//        }
//        try {
//            PublicKey publicKey = readPublic(publicKeyPath);
//            Signature sign = Signature.getInstance(ALGORITHM);
//            sign.initVerify(publicKey);
//            sign.update(srcData.getBytes(CHARSET_ENCODING));
//            return sign.verify(Base64.getDecoder().decode(signedData));
//        } catch (Exception e) {
//            log.info("验签verify出现异常",e);
//        }
//        return false;
//    }
//
//
//    /**
//     * 读取公钥
//     *
//     * @param publicKeyPath
//     * @return
//     */
//    private static PublicKey readPublic(String publicKeyPath) {
//        if (publicKeyPath == null) {
//            return null;
//        }
//        PublicKey pk = null;
//        FileInputStream bais = null;
//        try {
//            CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
//            bais = new FileInputStream(publicKeyPath);
//            X509Certificate cert = (X509Certificate) certificatefactory.generateCertificate(bais);
//            pk = cert.getPublicKey();
//        } catch (CertificateException e) {
//            log.error("读取公钥readPublic出现CertificateException异常",e);
//        } catch (FileNotFoundException e) {
//            log.error("读取公钥readPublic出现FileNotFoundException异常",e);
//        } finally {
//            if (bais != null) {
//                try {
//                    bais.close();
//                } catch (IOException e) {
//                    log.error("读取公钥readPublic出现IOException异常",e);
//                }
//            }
//        }
//        return pk;
//    }
//}
//
//@Slf4j
//public class WeiXinUtil {
//    public static String getToken(String method, String url, String body, String merchantId, String certSerialNo, String keyPath) throws Exception {
//        HttpUrl httpurl = HttpUrl.parse(url);
//        String nonceStr = StringUtil.getRandomKey(32);
//        long timestamp = System.currentTimeMillis() / 1000;
//        if (StringUtils.isEmpty(body)) {
//            body = "";
//        }
//        String message = buildMessage(method, httpurl, timestamp, nonceStr, body);
//        String signature = sign(message.getBytes("utf-8"), keyPath);
//        return "mchid=\"" + merchantId + "\","
//                + "nonce_str=\"" + nonceStr + "\","
//                + "timestamp=\"" + timestamp + "\","
//                + "serial_no=\"" + certSerialNo + "\","
//                + "signature=\"" + signature + "\"";
//    }
//
//    public static String sign(byte[] message, String keyPath) throws Exception {
//        Signature sign = Signature.getInstance("SHA256withRSA");
//        sign.initSign(getPrivateKey(keyPath));
//        sign.update(message);
//        return Base64.getEncoder().encodeToString(sign.sign());
//    }
//
//    public static String buildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {
//        String canonicalUrl = url.encodedPath();
//        if (url.encodedQuery() != null) {
//            canonicalUrl += "?" + url.encodedQuery();
//        }
//
//        return method + "\n"
//                + canonicalUrl + "\n"
//                + timestamp + "\n"
//                + nonceStr + "\n"
//                + body + "\n";
//    }
//
//    /**
//     * 获取私钥。
//     *
//     * @param filename 私钥文件路径  (required)
//     * @return 私钥对象
//     */
//    public static PrivateKey getPrivateKey(String filename) throws IOException {
//
//        String content = new String(Files.readAllBytes(Paths.get(filename)), "utf-8");
//        try {
//            String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
//                    .replace("-----END PRIVATE KEY-----", "")
//                    .replaceAll("\\s+", "");
//
//            KeyFactory kf = KeyFactory.getInstance("RSA");
//            return kf.generatePrivate(
//                    new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
//        } catch (NoSuchAlgorithmException e) {
//            throw new RuntimeException("当前Java环境不支持RSA", e);
//        } catch (InvalidKeySpecException e) {
//            throw new RuntimeException("无效的密钥格式");
//        }
//    }
//
//    //发送代金券v3版
//    public static String sendCoupon(String mchid, String url, String stockId, String appId, String openid) throws Exception {
//        String replaceUrl = url.replace("{}", openid);
//        String result = "";
////        String key = StringUtil.getRandomKey(6);
////        String s = DateUtil.currentDate();
////        String partnerTradeNo = mchid + s + key;
//        String partnerTradeNo = mchid + "1100022";
//        log.info("商户单据号:" + partnerTradeNo);
//        //商户证书序列号
//        String WX_SERIAL_NO = "467AD5AC9B1AD5784C60BB0FBB5E4F8DFD59CCA9";
//        // 商户证书签名私钥路径（最好不要有中文）
//        String keyPath = "D:\\wxpert\\apiclient_key.pem";
//        HttpClient client = HttpClients.createDefault();
//        Map<String, String> paramMap = new HashMap<>();
////        paramMap.put("stock_id", "10190992");
////        paramMap.put("out_request_no", partnerTradeNo);
////        paramMap.put("appid", "wxb9472f16ffb7c61a");
////        paramMap.put("stock_creator_mchid", mchid);
//        paramMap.put("stock_id", stockId);
//        paramMap.put("out_request_no", partnerTradeNo);
//        paramMap.put("appid", appId);
//        paramMap.put("stock_creator_mchid", mchid);
//        List<X509Certificate> certificateList = PublicKeyUtil.getCertByAPI(mchid, WxApiEnum.GET_CERT.getUrl(), 2, null, WX_SERIAL_NO, keyPath);
//        log.info("获取微信平台的证书结果certificateList={}", certificateList);
//        Boolean checkSign = CheckSignUtil.getCheckSign(mchid, WxApiEnum.GET_CERT.getUrl(), 2, null, WX_SERIAL_NO, keyPath);
//        log.info("验签结果checkSign={}", checkSign);
//        HttpPost httpPost = new HttpPost(replaceUrl);
//        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
//        httpPost.addHeader("Accept", "application/json");
//        httpPost.addHeader("Authorization", "WECHATPAY2-SHA256-RSA2048" + " "
//                + getToken("POST", replaceUrl, JSONObject.toJSONString(paramMap), mchid, WX_SERIAL_NO, keyPath));
//        httpPost.setEntity(new StringEntity(JSONObject.toJSONString(paramMap), "UTF-8"));
//        try {
//            HttpEntity entity = client.execute(httpPost).getEntity();
//            if (entity != null) {
//                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
//                StringBuffer resultBody = new StringBuffer();
//                String text;
//                while ((text = bufferedReader.readLine()) != null) {
//                    resultBody.append(text);
//
//                }
//                result = resultBody.toString();
//            }
//            EntityUtils.consume(entity);
//            log.info("====返回的结果===", result);
//        } catch (Exception e) {
//            log.error("发送代金券v3版异常", e);
//        }
//        return result;
//    }
//
//}
//
